<template>
  <el-dialog :model-value="visible" :title="title" width="500px" @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="收货人" prop="receiver_name">
        <el-input v-model="formData.receiver_name" placeholder="请输入收货人姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="receiver_mobile">
        <el-input
          v-model="formData.receiver_mobile"
          placeholder="请输入11位手机号"
          maxlength="11"
        />
      </el-form-item>

      <el-form-item label="所在地区" prop="region">
        <el-cascader
          v-model="formData.region"
          :options="regionOptions"
          :props="{ expandTrigger: 'hover' }"
          placeholder="请选择省/市/区"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="detailed_address">
        <el-input
          v-model="formData.detailed_address"
          type="textarea"
          placeholder="请输入详细地址"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="设为默认" prop="is_default">
        <el-switch v-model="formData.is_default" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addressApi, type Address, type AddressParams } from '@/api/address'

// 定义组件属性
const props = defineProps<{
  visible: boolean
  title: string
  address?: Address | null
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 表单数据
const formData = reactive({
  receiver_name: '',
  receiver_mobile: '',
  region: [] as string[],
  detailed_address: '',
  is_default: false,
})

// 地区选项（示例数据）
const regionOptions = [
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' },
          { value: '朝阳区', label: '朝阳区' },
          { value: '丰台区', label: '丰台区' },
          { value: '石景山区', label: '石景山区' },
        ],
      },
    ],
  },
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' },
          { value: '长宁区', label: '长宁区' },
          { value: '静安区', label: '静安区' },
          { value: '普陀区', label: '普陀区' },
        ],
      },
    ],
  },
  // 可以添加更多省份和城市数据
]

// 表单验证规则
const formRules = reactive<FormRules>({
  receiver_name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  receiver_mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' },
  ],
  region: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  detailed_address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
})

// 监听地址数据变化
watch(
  () => props.address,
  (newAddress) => {
    if (newAddress) {
      formData.receiver_name = newAddress.receiver_name
      formData.receiver_mobile = newAddress.receiver_mobile
      formData.region = [newAddress.province, newAddress.city, newAddress.district]
      formData.detailed_address = newAddress.detailed_address
      formData.is_default = newAddress.is_default
    } else {
      // 重置表单
      formData.receiver_name = ''
      formData.receiver_mobile = ''
      formData.region = []
      formData.detailed_address = ''
      formData.is_default = false
    }
  },
  { immediate: true },
)

// 关闭弹框
const handleClose = () => {
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      // 构造请求参数
      const params: AddressParams = {
        receiver_name: formData.receiver_name,
        receiver_mobile: formData.receiver_mobile,
        province: formData.region[0],
        city: formData.region[1],
        district: formData.region[2],
        detailed_address: formData.detailed_address,
        is_default: formData.is_default,
      }

      if (props.address?.address_id) {
        // 更新地址
        await addressApi.updateAddress(parseInt(props.address.address_id, 10), params)
        ElMessage.success('地址更新成功')
      } else {
        // 创建地址
        await addressApi.createAddress(params)
        ElMessage.success('地址添加成功')
      }

      // 关闭弹框并触发成功事件
      handleClose()
      emit('success')
    } catch (error: any) {
      console.error('操作失败:', error)
      ElMessage.error(error.message || '操作失败')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
